package 面试2025.腾讯音乐;

import 面试2025.Test;

import java.util.*;

/**
 * 当时截图输入和输出,没说返回树的root，我的写法只能算输出成功
 */
public class 翻转二叉树 {

    /**
     * 当时我的写法
     */
    public List<Integer> levelOrder(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> level = new ArrayList<>();
            int levelCount = queue.size();
            for(int i = 0;i < levelCount;i++){
                TreeNode node = queue.poll();
                level.add(node.val);
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            Collections.reverse(level);
            res.addAll(level);
        }
        for (Integer i : res) {
            System.out.print(i + "-");
        }
        return res;
    }

    /**
     * 正确做法
     */
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> level = new ArrayList<>();
            int levelCount = queue.size();
            for(int i = 0;i < levelCount;i++){
                TreeNode node = queue.poll();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
        }
        return root;
    }
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
